import axios from 'axios'
import { Message,Loading  } from 'element-ui'
import axiosRetry from 'axios-retry'
import {LoadingInstance,closeLoading} from './requestLoading'
import store from '@/store'
import router from '@/router'


const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

//超时请求重发
axiosRetry(service, {
  retries: 2,                       // 设置自动发送请求次数
  retryDelay: (retryCount) => {
    return retryCount * 1000;      // 重复请求延迟
  },
  shouldResetTimeout: true,       //  重置超时时间
  retryCondition: (error) => {//true为打开自动发送请求，false为关闭自动发送请求
    error.config.baseURL = ''
    if (error.message.includes("timeout")) {
      return true;
    } else {
      return false;
    };
  }
});
service.interceptors.request.use(
  config => {
    const token = store.getters.token
    if (token) {
      config.headers.Authorization = 'Bearer ' + token
    }
    LoadingInstance._count++;
    if(LoadingInstance._count === 1) {
      LoadingInstance._target = Loading.service();
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {   
   closeLoading()
    const { success, message } = response.data
    if (success) {
      return response.data
    } else {
      Message.error(message)
      return Promise.reject(message)
    }
 
  },
  error => {
    closeLoading()
     //token过期 
     if (error.response?.data?.code === 10002) {
      store.dispatch('user/logoutActions')
      router.replace({
        path: '/login',
        query: {
          redirect: router.currentRoute.fullPath
        }
      })//登录未遂
    }
    return Promise.reject(error)
  }
)

export default service
